package com.action.gulimall.order.service.impl;

import com.action.common.constant.MqConstant;
import com.action.common.constant.OrderConstant;
import com.action.common.to.mq.OrderTo;
import com.action.common.to.mq.SeckillOrderTo;
import com.action.common.utils.R;
import com.action.common.vo.MemberResponseVo;
import com.action.gulimall.order.entity.PaymentInfoEntity;
import com.action.gulimall.order.enums.OrderStatusEnum;
import com.action.gulimall.order.entity.OrderItemEntity;
import com.action.gulimall.order.interceptor.LoginInterceptor;
import com.action.gulimall.order.service.OrderItemService;
import com.action.gulimall.order.service.PaymentInfoService;
import com.action.gulimall.order.service.feign.CartFeignService;
import com.action.gulimall.order.service.feign.MemberFeignService;
import com.action.gulimall.order.service.feign.ProductFeignService;
import com.action.gulimall.order.service.feign.WareFeignService;
import com.action.gulimall.order.to.OrderCreateTo;
import com.action.gulimall.order.vo.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.action.common.utils.PageUtils;
import com.action.common.utils.Query;

import com.action.gulimall.order.dao.OrderDao;
import com.action.gulimall.order.entity.OrderEntity;
import com.action.gulimall.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Slf4j
@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {
    private ThreadLocal<OrderSubmitVo> confirmVoThreadLocal = new ThreadLocal<>();
    private ThreadLocal<MemberResponseVo> memberResponseVoThreadLocal = new ThreadLocal<>();
    @Autowired
    MemberFeignService memberFeignService;
    @Autowired
    CartFeignService cartFeignService;
    @Autowired
    WareFeignService wareFeignService;
    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    OrderItemService orderItemService;
    @Autowired
    PaymentInfoService paymentInfoService;

    @Value(value = "${order_token_script}")
    String order_token_script;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVo toTrade() {
        OrderConfirmVo orderConfirmVo = new OrderConfirmVo();
        //获取当前用户
        MemberResponseVo memberVo = LoginInterceptor.threadLocal.get();

        //获取当前用户的收货地址
        R r = memberFeignService.getMemberAddress(memberVo.getId().toString());
        List<MemberAddressVo> memberAddressVos = r.getData(new TypeReference<List<MemberAddressVo>>(){}).get();
        if(r.getCode()!=0){
            log.error("远程获取当前用户["+memberVo.getId()+"]的收货地址出现异常,异常信息:"+r.getMsg());
            memberAddressVos = new ArrayList<MemberAddressVo>();
        }
        orderConfirmVo.setMemberAddressVos(memberAddressVos);
        //获取当前用户的购物项
        R r1 = cartFeignService.getCheckedCartItems();
        List<Long> skuIds = new ArrayList<Long>();
        List<OrderItemVo> orderItemVos = r1.getData(new TypeReference<List<OrderItemVo>>(){}).get();
        if(r1.getCode()!=0){
            orderItemVos = new ArrayList<OrderItemVo>();
            log.error("远程获取获取当前用户["+memberVo.getId()+"]的购物项出现异常,异常信息:"+r.getMsg());
        }
        orderConfirmVo.setItems(orderItemVos);
        orderItemVos.forEach(item->{
            skuIds.add(item.getSkuId());
        });
        //获取用户购物项的库存情况
        Map<Long,Boolean> stocksMap =new HashMap<Long,Boolean>();
        R r2 = wareFeignService.skuIdHasStock(skuIds);
        //List<SkuHasStockVo> stocks = ((List<SkuHasStockVo>)r2.get("data"));
        List<SkuHasStockVo> stocks = r2.getData(new TypeReference<List<SkuHasStockVo>>(){}).get();
        if(r2.getCode()!=0){
            log.error("远程获取获取当前用户["+memberVo.getId()+"]的购物项出现异常,异常信息:"+r.getMsg());
            for (Long skuId : skuIds) {
                stocksMap.put(skuId, Boolean.FALSE);
            }
        }
        stocks.forEach(stock->{
            stocksMap.put(stock.getSkuId(), stock.getHasStock());
        });
        orderConfirmVo.setStocks(stocksMap);
        //3、查询用户积分
        Integer integration = memberVo.getIntegration();
        orderConfirmVo.setIntegration(integration);

        //4、价格数据自动计算

        //TODO 5、防重令牌(防止表单重复提交)
        //为用户设置一个token，三十分钟过期时间（存在redis）
        String token = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX+memberVo.getId(),token,30, TimeUnit.MINUTES);
        orderConfirmVo.setOrderToken(token);
        return orderConfirmVo;
    }

    //@GlobalTransactional(rollbackFor = Exception.class)
    @Transactional
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo vo) {
        confirmVoThreadLocal.set(vo);
        SubmitOrderResponseVo responseVo = new SubmitOrderResponseVo();
        responseVo.setCode(0);
        //获取当前用户
        MemberResponseVo memberVo = LoginInterceptor.threadLocal.get();
        //原子对比并删除令牌
        //String script ="if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        Long execute = redisTemplate.execute(new DefaultRedisScript<Long>(order_token_script, Long.class)
                , Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberVo.getId())
                , vo.getOrderToken());
        //String token = redisTemplate.opsForValue().get(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberVo.getId());
        //验令牌
        if(execute.intValue()==0) {
            //令牌验证失败
            responseVo.setCode(1);
            //return responseVo;
        }else{
            //创建订单、订单项等信息
            OrderCreateTo order = createOrder();
            //验价
            if(Math.abs(order.getPayPrice().subtract(vo.getPayPrice()).doubleValue())>0.01){
                //验价失败
                responseVo.setCode(2);
                //return responseVo;
            }else{
                //验价成功 保存订单
                ((OrderServiceImpl)AopContext.currentProxy()).saveOrder(order);
                //saveOrder(order);
                //远程锁库存
                //4、库存锁定,只要有异常，回滚订单数据
                //订单号、所有订单项信息(skuId,skuNum,skuName)
                WareSkuLockVo lockVo = new WareSkuLockVo();
                lockVo.setOrderSn(order.getOrder().getOrderSn());
                //获取出要锁定的商品数据信息
                List<OrderItemVo> orderItemVos = order.getOrderItems().stream().map((item) -> {
                    OrderItemVo orderItemVo = new OrderItemVo();
                    orderItemVo.setSkuId(item.getSkuId());
                    orderItemVo.setCount(item.getSkuQuantity());
                    orderItemVo.setTitle(item.getSkuName());
                    return orderItemVo;
                }).collect(Collectors.toList());
                lockVo.setLocks(orderItemVos);
                //调用库存服务锁库存 并记录库存锁定记录
                R r = wareFeignService.orderLockStock(lockVo);
                if(r.getCode()!=0){
                    //锁定库存失败
                    responseVo.setCode(3);
                    log.info("orderSn="+order.getOrder().getOrderSn()+"锁定库存失败,异常信息:"+ JSON.toJSONString(r));
                    //return responseVo;
                }else{
                    //删除购物车对应的信息

                    //锁定成功
                    responseVo.setOrder(order.getOrder());
                    //发送创建订单消息给mq   订单超时自动解锁
                    rabbitTemplate.convertAndSend(
                            MqConstant.ORDER_EXCHANGE_NAME,
                            MqConstant.ORDER_CREATE_ROUTINGKEY,
                            order.getOrder(),
                            new CorrelationData(order.getOrder().getOrderSn()));
                }
            }
        }
        confirmVoThreadLocal.remove();
        return responseVo;
    }

    @Override
    public OrderEntity getOrderEntityByOrderSn(Long orderSn) {
        return this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
    }
    //取消订单
    @Override
    public void closeOrder(OrderEntity orderEntity) {
        //关闭订单之前先查询一下数据库，判断此订单状态是否已支付
        OrderEntity orderInfo = this.getOne(new QueryWrapper<OrderEntity>().
                eq("order_sn",orderEntity.getOrderSn()));
        if (orderInfo.getStatus().equals(OrderStatusEnum.CREATE_NEW.getCode())) {
            //代付款状态进行关单
            OrderEntity orderUpdate = new OrderEntity();
            orderUpdate.setId(orderInfo.getId());
            orderUpdate.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(orderUpdate);

            /**
             * 发送消息给MQ 通知解锁库存 防止订单服务卡顿，导致订单状态消息一直改不了，库存优先到期，查订单状态新建，什么都不处理
             * 导致卡顿的订单，永远都不能解锁库存
             */
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(orderInfo, orderTo);
            try{
                //TODO 确保每个消息发送成功，给每个消息做好日志记录，(给数据库保存每一个详细信息)保存每个消息的详细信息
                rabbitTemplate.convertAndSend(MqConstant.ORDER_EXCHANGE_NAME, MqConstant.ORDER_STOCK_RELEASE_ROUTINGKEY, orderTo);
            } catch (Exception e) {
                //TODO 定期扫描数据库，重新发送失败的消息
            }
        }
    }

    @Override
    public PayVo getOrderPay(String orderSn) {
        PayVo payVo = new PayVo();
        OrderEntity orderInfo = this.getOrderByOrderSn(orderSn);
        //保留两位小数点，向上取值
        BigDecimal payAmount = orderInfo.getPayAmount().setScale(2, BigDecimal.ROUND_UP);
        payVo.setTotal_amount(payAmount.toString());
        payVo.setOut_trade_no(orderInfo.getOrderSn());

        //查询订单项的数据
        List<OrderItemEntity> orderItemInfo = orderItemService.list(
                new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        OrderItemEntity orderItemEntity = orderItemInfo.get(0);
        payVo.setBody(orderItemEntity.getSkuAttrsVals());

        payVo.setSubject(orderItemEntity.getSkuName());

        return payVo;
    }

    @Override
    public String handlePayResult(PayAsyncVo asyncVo) {
        //保存交易流水信息
        PaymentInfoEntity paymentInfo = new PaymentInfoEntity();
        paymentInfo.setOrderSn(asyncVo.getOut_trade_no());
        paymentInfo.setAlipayTradeNo(asyncVo.getTrade_no());
        paymentInfo.setTotalAmount(new BigDecimal(asyncVo.getBuyer_pay_amount()));
        paymentInfo.setSubject(asyncVo.getBody());
        paymentInfo.setPaymentStatus(asyncVo.getTrade_status());
        paymentInfo.setCreateTime(new Date());
        paymentInfo.setCallbackTime(asyncVo.getNotify_time());
        //添加到数据库中
        this.paymentInfoService.save(paymentInfo);

        //修改订单状态
        //获取当前状态
        String tradeStatus = asyncVo.getTrade_status();
        if (tradeStatus.equals("TRADE_SUCCESS") || tradeStatus.equals("TRADE_FINISHED")){
            //支付成功状态
            String orderSn = asyncVo.getOut_trade_no(); //获取订单号
            this.updateOrderStatus(orderSn,OrderStatusEnum.PAYED.getCode(),OrderConstant.PayType.ALIPAY.getMsg());
        }
        return "success";
    }

    @Override
    public String asyncNotify(String notifyData) {

        return null;
    }

    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        QueryWrapper<OrderEntity> queryWrapper = new QueryWrapper<>();
        MemberResponseVo memberResponseVo = LoginInterceptor.threadLocal.get();
        if(memberResponseVo==null){//支付宝支付回调
            String orderSn = (String)params.get("out_trade_no");
            if(!StringUtils.isEmpty(orderSn)){
                queryWrapper.eq("order_sn",orderSn);
            }
        }else{
            queryWrapper.eq("member_id",memberResponseVo.getId()).orderByDesc("create_time");
        }
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                queryWrapper
        );

        //遍历所有订单集合
        List<OrderEntity> orderEntityList = page.getRecords().stream().map(order -> {
            //根据订单号查询订单项里的数据
            List<OrderItemEntity> orderItemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>()
                    .eq("order_sn", order.getOrderSn()));
            order.setOrderItemEntityList(orderItemEntities);
            return order;
        }).collect(Collectors.toList());

        page.setRecords(orderEntityList);

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void createSeckillOrder(SeckillOrderTo seckillOrderTo){

        //TODO 保存订单信息
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(seckillOrderTo.getOrderSn());
        orderEntity.setMemberId(seckillOrderTo.getMemberId());
        orderEntity.setCreateTime(new Date());
        BigDecimal totalPrice = seckillOrderTo.getSeckillPrice().multiply(BigDecimal.valueOf(seckillOrderTo.getNum()));
        orderEntity.setPayAmount(totalPrice);
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        //保存订单
        this.save(orderEntity);
        //保存订单项信息
        OrderItemEntity orderItem = new OrderItemEntity();
        orderItem.setOrderSn(seckillOrderTo.getOrderSn());
        orderItem.setRealAmount(totalPrice);
        orderItem.setSkuQuantity(seckillOrderTo.getNum());

        //保存商品的spu信息
        R spuInfo = productFeignService.getSpuInfoBySkuId(seckillOrderTo.getSkuId());
        SpuInfoVo spuInfoData = spuInfo.getData( new TypeReference<SpuInfoVo>() {
        }).get();
        orderItem.setSpuId(spuInfoData.getId());
        orderItem.setSpuName(spuInfoData.getSpuName());
        orderItem.setSpuBrand(spuInfoData.getBrandName());
        orderItem.setCategoryId(spuInfoData.getCatalogId());
        //保存订单项数据
        orderItemService.save(orderItem);
        OrderCreateTo orderCreateTo = new OrderCreateTo();
        orderCreateTo.setOrder(orderEntity);
        List<OrderItemEntity> orderItems =new ArrayList<OrderItemEntity>();
        orderItems.add(orderItem);
        orderCreateTo.setOrderItems(orderItems);
        orderCreateTo.setFare(BigDecimal.ZERO);
        orderCreateTo.setPayPrice(totalPrice);
        //发送创建订单消息给mq  订单超时自动解锁
        rabbitTemplate.convertAndSend(
                MqConstant.ORDER_EXCHANGE_NAME,
                MqConstant.ORDER_CREATE_ROUTINGKEY,
                orderCreateTo,new CorrelationData(seckillOrderTo.getOrderSn()));
    }

    @Transactional
    public void updateOrderStatus(String orderSn, Integer status, String payType) {
        this.baseMapper.updateOrderStatus(orderSn,status,payType);
    }

    private OrderEntity getOrderByOrderSn(String orderSn) {
        return this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
    }

    @Transactional
    public void saveOrder(OrderCreateTo orderCreateTo) {
        //获取订单信息
        OrderEntity order = orderCreateTo.getOrder();
        order.setModifyTime(new Date());
        order.setCreateTime(new Date());
        //保存订单
        this.baseMapper.insert(order);

        //获取订单项信息
        List<OrderItemEntity> orderItems = orderCreateTo.getOrderItems();
        //批量保存订单项数据
        orderItemService.saveBatch(orderItems);
    }

    @Transactional
    public OrderCreateTo createOrder() {
        OrderCreateTo orderCreateTo = new OrderCreateTo();
        //创建订单号
        String orderSn = IdWorker.getTimeId();
        //构建OrderEntity
        OrderEntity orderEntity =  buildOrderEntity(orderSn);
        orderCreateTo.setOrder(orderEntity);
        //构建OrderItemEntitys
        List<OrderItemEntity> orderItemEntities = buildOrderItems(orderSn);
        orderCreateTo.setOrderItems(orderItemEntities);
        //计算价格
        computePrice(orderCreateTo,orderItemEntities);
        return orderCreateTo;
    }

    private void computePrice(OrderCreateTo orderCreateTo, List<OrderItemEntity> orderItemEntities) {
        OrderEntity orderEntity = orderCreateTo.getOrder();
        //总价
        BigDecimal total = new BigDecimal("0.0");
        //优惠价
        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal intergration = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");

        //积分、成长值
        Integer integrationTotal = 0;
        Integer growthTotal = 0;

        //订单总额，叠加每一个订单项的总额信息
        for (OrderItemEntity orderItem : orderItemEntities) {
            //优惠价格信息
            coupon = coupon.add(orderItem.getCouponAmount());
            promotion = promotion.add(orderItem.getPromotionAmount());
            intergration = intergration.add(orderItem.getIntegrationAmount());

            //总价
            total = total.add(orderItem.getRealAmount());

            //积分信息和成长值信息
            integrationTotal += orderItem.getGiftIntegration();
            growthTotal += orderItem.getGiftGrowth();

        }
        //1、订单价格相关的
        orderEntity.setTotalAmount(total);
        //设置应付总额(总额+运费)
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        orderCreateTo.setPayPrice(orderEntity.getPayAmount());
        orderCreateTo.setFare(orderEntity.getFreightAmount());
        orderEntity.setCouponAmount(coupon);
        orderEntity.setPromotionAmount(promotion);
        orderEntity.setIntegrationAmount(intergration);

        //设置积分成长值信息
        orderEntity.setIntegration(integrationTotal);
        orderEntity.setGrowth(growthTotal);

        //设置删除状态(0-未删除，1-已删除)
        orderEntity.setDeleteStatus(0);
    }

    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        List<OrderItemEntity> orderItemEntities = new ArrayList<OrderItemEntity>();
        //最后确定每个购物项的价格
        R checkedCartItems = cartFeignService.getCheckedCartItems();
        List<OrderItemVo> currentCartItems = checkedCartItems.getData(new TypeReference<List<OrderItemVo>>(){}).get();
        if (currentCartItems != null && currentCartItems.size() > 0) {
            orderItemEntities = currentCartItems.stream().map((item) -> {
                //构建订单项数据
                OrderItemEntity orderItemEntity = builderOrderItem(item);
                orderItemEntity.setOrderSn(orderSn);

                return orderItemEntity;
            }).collect(Collectors.toList());
        }
        return orderItemEntities;
    }

    private OrderItemEntity builderOrderItem(OrderItemVo items) {
        OrderItemEntity orderItemEntity = new OrderItemEntity();

        //1、商品的spu信息
        Long skuId = items.getSkuId();
        //获取spu的信息
        R spuInfo = productFeignService.getSpuInfoBySkuId(skuId);
        SpuInfoVo spuInfoData = spuInfo.getData(new TypeReference<SpuInfoVo>(){}).get();
        orderItemEntity.setSpuId(spuInfoData.getId());
        orderItemEntity.setSpuName(spuInfoData.getSpuName());
        orderItemEntity.setSpuBrand(spuInfoData.getBrandName());
        orderItemEntity.setCategoryId(spuInfoData.getCatalogId());

        //2、商品的sku信息
        orderItemEntity.setSkuId(skuId);
        orderItemEntity.setSkuName(items.getTitle());
        orderItemEntity.setSkuPic(items.getImage());
        orderItemEntity.setSkuPrice(items.getPrice());
        orderItemEntity.setSkuQuantity(items.getCount());

        //使用StringUtils.collectionToDelimitedString将list集合转换为String
        String skuAttrValues = StringUtils.collectionToDelimitedString(items.getSkuAttrValues(), ";");
        orderItemEntity.setSkuAttrsVals(skuAttrValues);

        //3、商品的优惠信息

        //4、商品的积分信息
        orderItemEntity.setGiftGrowth(items.getPrice().multiply(new BigDecimal(items.getCount())).intValue());
        orderItemEntity.setGiftIntegration(items.getPrice().multiply(new BigDecimal(items.getCount())).intValue());

        //5、订单项的价格信息
        orderItemEntity.setPromotionAmount(BigDecimal.ZERO);
        orderItemEntity.setCouponAmount(BigDecimal.ZERO);
        orderItemEntity.setIntegrationAmount(BigDecimal.ZERO);

        //当前订单项的实际金额.总额 - 各种优惠价格
        //原来的价格
        BigDecimal origin = orderItemEntity.getSkuPrice().multiply(new BigDecimal(orderItemEntity.getSkuQuantity().toString()));
        //原价减去优惠价得到最终的价格
        BigDecimal subtract = origin.subtract(orderItemEntity.getCouponAmount())
                .subtract(orderItemEntity.getPromotionAmount())
                .subtract(orderItemEntity.getIntegrationAmount());
        orderItemEntity.setRealAmount(subtract);
        return orderItemEntity;
    }

    private OrderEntity buildOrderEntity(String orderSn) {
        //获取当前用户登录信息
        MemberResponseVo memberResponseVo = LoginInterceptor.threadLocal.get();
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setMemberId(memberResponseVo.getId());
        orderEntity.setOrderSn(orderSn);
        orderEntity.setMemberUsername(memberResponseVo.getUsername());

        //远程获取收货地址和运费信息
        OrderSubmitVo orderSubmitVo = confirmVoThreadLocal.get();
        R fareAddressVo = wareFeignService.getFare(orderSubmitVo.getAddrId());
        FareVo fareResp = fareAddressVo.getData(new TypeReference<FareVo>() {}).get();

        //获取到运费信息
        BigDecimal fare = fareResp.getFare();
        orderEntity.setFreightAmount(fare);

        //获取到收货地址信息
        MemberAddressVo address = fareResp.getAddress();
        //设置收货人信息
        orderEntity.setReceiverName(address.getName());
        orderEntity.setReceiverPhone(address.getPhone());
        orderEntity.setReceiverPostCode(address.getPostCode());
        orderEntity.setReceiverProvince(address.getProvince());
        orderEntity.setReceiverCity(address.getCity());
        orderEntity.setReceiverRegion(address.getRegion());
        orderEntity.setReceiverDetailAddress(address.getDetailAddress());

        //设置订单相关的状态信息
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        orderEntity.setAutoConfirmDay(7);
        orderEntity.setConfirmStatus(0);
        return orderEntity;
    }

}